﻿using System.Text;
using Microsoft.AspNetCore.Mvc;
using SSO.OAuth.Models;
using SSO.OAuth.Util;

namespace SSO.OAuth.Controllers;

/// <summary>
/// 登录页面
/// </summary>
public class SsoController (IJWTService jwtService, IHttpClientFactory httpClientFactory, Cachelper cacheHelper)
    : Controller {
    public IActionResult Login () {
        return View();
    }

    /// <summary>
    /// 获取授权码
    /// </summary>
    [HttpPost]
    public ResponseModel<string> GetCode ([FromBody] GetCoderRequest request) {
        return jwtService.GetCode(request.clientId, request.userName, request.passWord);
    }

    /// <summary>
    /// 根据授权码,获取Token
    /// </summary>
    [HttpPost]
    public ResponseModel<GetTokenDTO> GetToken ([FromBody] GetTokenRequestDto request) {
        return jwtService.GetTokenWithRefresh(request.authCode);
    }

    /// <summary>
    /// 根据会话code获取授权码
    /// </summary>
    [HttpPost]
    public ResponseModel<string> GetCodeBySessionCode ([FromBody] GetCodeBySessionCodeRequest request) {
        return jwtService.GetCodeBySessionCode(request.clientId, request.sessionCode);
    }

    /// <summary>
    /// 退出登录页面
    /// </summary>
    public IActionResult LogOut () {
        return View();
    }

    /// <summary>
    /// 退出登录
    /// </summary>
    [HttpPost]
    public async Task<ResponseModel> LogOutApp ([FromBody] LogOutRequest request) {
        //删除全局会话
        string sessionKey = $"SessionCode:{request.sessionCode}";
        cacheHelper.DeleteKey(sessionKey);
        var client = httpClientFactory.CreateClient();
        var param = new { request.sessionCode };
        string jsonData = System.Text.Json.JsonSerializer.Serialize(param);

        //这里实战中是用数据库或缓存取
        List<string> urls = [
            "https://localhost:7001/Account/LogOut",
            "https://localhost:7002/Account/LogOut"
        ];

        //这里可以异步mq处理，不阻塞返回
        foreach (var url in urls) {
            //web1退出登录
            var logOutResponse =
                await client.PostAsync(url, new StringContent(jsonData, Encoding.UTF8, "application/json"));
            string resultStr = await logOutResponse.Content.ReadAsStringAsync();
            ResponseModel response = System.Text.Json.JsonSerializer.Deserialize<ResponseModel>(resultStr);
            Console.WriteLine(response.code == 0
                ? $"url:{url},会话Id:{request.sessionCode},退出登录成功"
                : $"url:{url},会话Id:{request.sessionCode},退出登录失败");
        }

        return new ResponseModel().SetSuccess();
    }
}